ScreenActionHelper = {}
ScreenActionHelper.__index = ScreenActionHelper
 
function ScreenActionHelper.new()
    local instance = {

    }
    
    setmetatable(instance, ScreenActionHelper)
    return instance
end

function ScreenActionHelper:mainmenuAction(x, y)
  local iX, iY = MainLayer:wndToWorld(x, y)
  local prop = mainMenuPartition:propForPoint(iX, iY, 0, MOAILayer.SORT_PRIORITY_ASCENDING)    
  local chosenOption = mainMenuLinks[prop]
  
  if prop ~= nil then
    audio:buttonConfirm()
    if chosenOption == "start" then
      showChooseLevel()
    elseif chosenOption == "guide" then
      showGuide()
    end
  end
end

function ScreenActionHelper:guideAction(x, y)
  local iX, iY = MainLayer:wndToWorld(x, y)
  local prop = guidePartition:propForPoint(iX, iY, 0, MOAILayer.SORT_PRIORITY_ASCENDING)
  local isBackButton = false
  
  if guideScreen == 1 then
    if prop == backButtonProp then
      isBackButton = true
      tileGuideProp:setVisible(false)
    end
    
    if isBackButton == true then
      audio:buttonBack()
      showMainMenu()
      return
    elseif prop ~= nil then
      camera:setLoc(0, 0)
    end
    
    if prop == forwardButtonProp then
      audio:buttonConfirm()
      unitGuideProp:setVisible(false)
      tileGuideProp:setVisible(true)
      guideScreen = 2
    end
  elseif guideScreen == 2 then
    if prop == forwardButtonProp then
      audio:buttonConfirm()
      tileGuideProp:setVisible(false)
      heroGuideProp:setVisible(true)
      forwardButtonProp:setVisible(false) 
      guideScreen = 3
    elseif prop == backButtonProp then
      audio:buttonBack()
      unitGuideProp:setVisible(true)
      tileGuideProp:setVisible(false)
      heroGuideProp:setVisible(false)
      guideScreen = 1
    end
  elseif guideScreen == 3 then
    if prop == backButtonProp then
      audio:buttonBack()
      tileGuideProp:setVisible(true)
      heroGuideProp:setVisible(false)
      forwardButtonProp:setVisible(true) 
      guideScreen = 2
    end
  end
end

function ScreenActionHelper:chooselevelAction(x, y)
  local iX, iY = MainLayer:wndToWorld(x, y)
  local prop = chooseLevelPartition:propForPoint(iX, iY, 0, MOAILayer.SORT_PRIORITY_ASCENDING)
  chosenLevel = chooseLevelLinks[prop]
  
  local isBackButton = false
  if prop == backButtonProp then
    isBackButton = true
  end
  if isBackButton == true then
    audio:buttonBack()
    showMainMenu()
  elseif prop ~= nil then
    camera:setLoc(0, 0)
    if chosenLevel == 1 or chosenLevel == 2 or chosenLevel == 3 or chosenLevel == 4 or chosenLevel == 5 or chosenLevel == 6 then
      startGame:startNewGame(chosenLevel)
      if audioTurnedOn == true then
        audio:playLevelBackgroundAudio(2)
      end
    end
  end
end

function ScreenActionHelper:gameAction(x, y)
  local iX, iY = MainLayer:wndToWorld(x,y)
  local prop = gamePartition:propForPoint(iX, iY, 0, MOAILayer.SORT_PRIORITY_ASCENDING)

  if doneButtonShowed == true then
    doneButtonProp:moveLoc(0, -50, 1)
    doneButtonShowed = false
    if prop == doneButtonProp then
      
      if tutEnd1 == true then MainLayer:removeProp(tutRed4) end
      if tutEnd2 == true then MainLayer:removeProp(tutBlue4) end
  
      endTurn()
    end
  end

  -- check mute
  if prop == speakerOnProp or prop == speakerOffProp then
    if audioTurnedOn == true then
      speakerOnProp:setVisible(false)
      speakerOffProp:setVisible(true)
      audio:stopLevelBackgroundAudio()
      audioTurnedOn = false
      return
    elseif audioTurnedOn == false then
      speakerOnProp:setVisible(true)
      speakerOffProp:setVisible(false)
      audio:playLevelBackgroundAudio(chosenLevel)
      audioTurnedOn = true
      return
    end
  end
  
  if settingsPropActive == false then
    if prop == settingsProp then
      
      local settingsScreen = MOAIGfxQuad2D.new()
      settingsScreen:setTexture("resources/graphics/ingame_menu/exitgame.png")
      settingsScreen:setRect(-175, -128, 128, 128)

      settingsScreenProp = MOAIProp2D.new()
      settingsScreenProp:setDeck(settingsScreen)
      settingsScreenProp:setLoc((baseScreenWidth / 2) + 32, 0)
      settingsScreenProp:moveLoc(0, -(baseScreenHeight / 2) + 32, 1)
      settingsScreenProp:setPriority(101)
      MainLayer:insertProp(settingsScreenProp)
      
      settingsPropActive = true
      
      return
    end
  elseif settingsPropActive == true then
    if x >= 350 and x <= 520 then
      if y >= 250 and y <= 300 then
        MainLayer:removeProp(settingsScreenProp)
        settingsPropActive = false
      elseif y >= 320 and y <= 380 then
        showMainMenu()
        audio:stopLevelBackgroundAudio()
        settingsPropActive = false
      end
    end
  end
  
  local list = self:getObjWithProps(x,y)
  local environmentsList = list[1]
  local buildingsList = list[2]
  local unitList = list[3]
  
  local tile = environmentsList[1]
  local tileProp = environmentsList[2]
  
  local b = tile:getBuilding()
  local e = tile:getWorldObject()
  local u = tile:getUnit()
  
  -- tutorial code    

  -- einde tutorial code
  
  
  if u ~= nil then
    selectedUnitRange = u
  end
  
  if rangeTurnedOn == true then   
    self:turnRangeOn(x, y, tile, tileProp,buildingsList, unitList[2]);
  end

  if unitList[2] ~= nil and unitList[1]:getOwnerObject() == currentPlayerTurn and unitList[1]:getHasMoved() == false and userCanClick == true then
    self:setUnit(unitList[1], unitList[2], tileProp, tile);
    if currentPlayerTurn == pl1 and tutTapMove1 == true then MainLayer:removeProp(tutRed3) end
    if currentPlayerTurn == pl2 and tutTapMove2 == true then MainLayer:removeProp(tutBlue3) end
     
    if currentPlayerTurn == pl1 and tutEnd1 == false and chosenLevel == 1 then
      tutEnd1 = true
      local image = MOAIGfxQuad2D.new()
      image:setTexture("resources/graphics/ingame_menu/tutorialred4.png")
      image:setRect(230, -300, 530, -250)

      tutRed4 = MOAIProp2D.new()
      tutRed4:setDeck(image)
      tutRed4:setPriority(1000)
      MainLayer:insertProp(tutRed4)
    end
    
    if currentPlayerTurn == pl2 and tutEnd2 == false and chosenLevel == 1 then
        tutEnd2 = true
        local image = MOAIGfxQuad2D.new()
        image:setTexture("resources/graphics/ingame_menu/tutorialblue4.png")
        image:setRect(230, -300, 530, -250)

        tutBlue4 = MOAIProp2D.new()
        tutBlue4:setDeck(image)
        tutBlue4:setPriority(1000)
        MainLayer:insertProp(tutBlue4)
      end
    
  end
  
if isUnitMoving == false then
  if chosenUnit ~= nil then
    if rangeTurnedOn == true then
      if chosenUnit:getType() == "Heavy_Horse" then
          if math.random(4) <= 2 then
            audio:playKnightSelect1()
          else
            audio:playKnightSelect2()
          end
      elseif chosenUnit:getType() == "SwordFighter" then
        if math.random(4) <= 2 then
          audio:playSwordFighterSelect1()
        else
          audio:playSwordFighterSelect2()
        end
      elseif chosenUnit:getType() == "Archer" then
        if math.random(4) <= 2 then
          audio:playArcherSelect1()
        else
          audio:playArcherSelect2()
        end
      end  
    end
  end
end

if chosenUnit ~= nil and chosenUnit:getHasAttacked() == false and chosenUnit:getHasMoved() == true and chosenUnit:getType() ~= "Archer" then
    if table.getn(attackProps) > 0 then
      if tile:getUnit() ~= nil then
        attackHelper:attack(x, y, tile, tileProp, unitList[2], true)
      else
        self:removeAttackRanges()
        if unitselectionProp ~= nil then
          MainLayer:removeProp(unitselectionProp)
          unitselectionProp = nil
        end
      end
    elseif unitList[1] ~= nil and unitList[1]:getOwnerObject() == currentPlayerTurn then
      if unitselectionProp == nil then
        self:showUnitSelection(chosenUnit)
        self:showAttackRanges(chosenUnit:getAttackRange(), chosenUnit:getRectangleValues())
      end
    end
  end
  
  if propOverlay ~= nil then
    buildingHelper:propOverLay(x, y)
  end 
  
  if b ~= nil then
    buildingHelper:buildingProps(tile, b, tileProp, buildingsList)
    if currentPlayerTurn == pl1 and tutRecruit1 == true then MainLayer:removeProp(tutRed1) end
    if currentPlayerTurn == pl2 and tutRecruit2 == true then MainLayer:removeProp(tutBlue1) end   
    
    if currentPlayerTurn == pl1 and tutTapIcon1 == false and chosenLevel == 1 then
      tutTapIcon1 = true
      local image = MOAIGfxQuad2D.new()
      image:setTexture("resources/graphics/ingame_menu/tutorialred2.png")
      image:setRect(400, -625, 650, -525)

      tutRed2 = MOAIProp2D.new()
      tutRed2:setDeck(image)
      tutRed2:setPriority(1000)
      MainLayer:insertProp(tutRed2)
    end
    
    if currentPlayerTurn == pl2 and tutTapIcon2 == false and chosenLevel == 1 then
      tutTapIcon2 = true
      local image = MOAIGfxQuad2D.new()
      image:setTexture("resources/graphics/ingame_menu/tutorialblue2.png")
      image:setRect(400, -625, 650, -525)

      tutBlue2 = MOAIProp2D.new()
      tutBlue2:setDeck(image)
      tutBlue2:setPriority(1000)
      MainLayer:insertProp(tutBlue2)
    end
    
  else
    if buildingSelectionProp ~= nil then
      MainLayer:removeProp(buildingSelectionProp)
      buildingSelectionProp = nil
    end
  end
end

function ScreenActionHelper:getObjWithProps(x, y)
  local iX, iY = MainLayer:wndToWorld(x, y)
  local props = {gamePartition:propListForPoint(iX, iY, 0, MOAILayer.SORT_PRIORITY_DESCENDING)}
  
  local result = {}
  local buildings = {}
  local environment = {}
  local units = {}
  
  local tile = nil
  local tileProp = nil
  
  for i, v in pairs(props) do
    temp = propToTileObject[v]
    if temp ~= nil then
      local typeObject = temp:getType()
      if typeObject == "Tile" then
        environment[1] = temp
        environment[2] = v
      elseif typeObject == "Castle-player1" or 
        typeObject == "Castle-player2" or 
        typeObject == "Castle-neutral" or 
        typeObject == "BarracksCavalry-player1" or 
        typeObject == "BarracksCavalry-player2" or 
        typeObject == "BarracksCavalry-neutral" or 
        typeObject == "BarracksMelee-player1" or
        typeObject == "BarracksMelee-player2" or 
        typeObject == "BarracksMelee-neutral" or 
        typeObject == "BarracksRange-player1" or 
        typeObject == "BarracksRange-player2" or 
        typeObject == "BarracksRange-neutral" or
        typeObject == "Headquarters-player1" or
        typeObject == "Headquarters-player2" or
        typeObject == "CapturePointBuilding-neutral" or
        typeObject == "CapturePointBuilding-player1" or
        typeObject == "CapturePointBuilding-player2" then
        buildings[1] = temp
        buildings[2] = v
      elseif typeObject == "Archer" or
        typeObject == "Crossbow" or
        typeObject == "Heavy_Horse" or
        typeObject == "Light_Horse" or
        typeObject == "Spearmen" or
        typeObject == "SpearThrower" or
        typeObject == "SwordFighter" then
        units[1] = temp
        units[2] = v
      end
    end
  end
    
  result[1] = environment
  result[2] = buildings
  result[3] = units
  
  return result
end

function ScreenActionHelper:setUnit(unitList1, unitList2, tileProp, tile)
    unitProp = unitList2
    selectedUnit = unitProp
    move = MovementHelper.new()
    lastTile = tile
    
    self:showUnitSelection(unitList1)
    
    if rangeTurnedOn == false and userCanClick == true then
      move:showRange(selectedUnitRange:getMoveRange(), tileProp:getRect())
      rangeTurnedOn = true
      chosenUnit = unitList1
      chosenUnitProp = unitProp
      self:showAttackRanges(chosenUnit:getAttackRange(), tileProp:getRect())
    end
end

function ScreenActionHelper:turnRangeOn(x, y, tile, tileProp, buildingsList, _clickedUnitProp) 
  local iX, iY = MainLayer:wndToWorld(x, y)
  local props = {gamePartition:propListForPoint(iX, iY, 0, MOAILayer.SORT_PRIORITY_ASCENDING)}
  
  for i, v in pairs(props) do
    for i=1, table.getn(rangeProps), 1 do
      local prop = rangeProps[i]
      if prop == v then
        local x1, y1, x2, y2 = prop:getRect()
        local pX1, pY1, pX2, pY2 = chosenUnit:getRectangleValues()
        
        local tempX = x2 - pX2
        local tempY = y1 - pY1          

        if userCanClick == true then
          self:removeAttackRanges()
          move:moveUnit(selectedUnit, tempX, tempY , 2)
          userCanClick = false
          
          if isFogOn == true then
            local fx1, fy1, fx2, fy2 = chosenUnit:getRectangleValues()
            foghelper:hideFogForProp(fx1, fy1, fx2, fy2, true)
          end
          chosenUnit:setRectangleValues(x1, y1, x2, y2)
          
          if isFogOn == true then
            local ffx1, ffy1, ffx2, ffy2 = chosenUnit:getRectangleValues()
            foghelper:hideFogForProp(ffx1, ffy1, ffx2, ffy2, false)
            foghelper:hideFogForCurrentPlayer()
          end
          chosenUnit:moveHealthBox(tempX, tempY)
          lastTile:setUnit(nil)
          tile:setUnit(chosenUnit)
          tileChosenUnitOn = tile
          chosenUnit:setHasMoved(true)
          chosenUnit:setTileUnitOn(tile)
          
          local timer = MOAITimer.new()
            timer:setMode(MOAITimer.NORMAL)
            timer:setSpan(1)
            timer:setListener(MOAITimer.EVENT_TIMER_END_SPAN, 
              function()  
                unitProp:setColor(1.0,1.0,1.0,0.60)
                table.insert(usedUnits, unitProp)
              end)      
          
          if chosenUnit:getType() ~= "Archer" then
            self:showAttackRanges(chosenUnit:getAttackRange(), x1, y1, x2, y2)
          end
          if table.getn(attackProps) <= 0 then
            chosenUnit:setHasAttacked(true)
            timer:start()
            self:removeAttackRanges()
            if unitselectionProp ~= nil then
              MainLayer:removeProp(unitselectionProp)
              unitselectionProp = nil
            end
          else
            unitselectionProp:moveLoc(tempX, tempY, 2)
          end
          
          local buildingUnitOn = tile:getBuilding()
          if buildingUnitOn ~= nil then
            if buildingUnitOn:getOwnerObject() ~= currentPlayerTurn then
              local list = {chosenUnit, buildingUnitOn, buildingsList[2]}
              table.insert(captureBuildingsList, list)
              buildingUnitOn:showCaptureTextbox(tileProp:getRect())
              
              if lastTile:getBuilding() ~= nil and lastTile:getBuilding():getOwnerObject() ~= currentPlayerTurn then
                captureBuilding:removeUnitFromCaptureList(chosenUnit)
              end
              elseif buildingUnitOn:getOwnerObject() == currentPlayerTurn then
              captureBuilding:removeUnitFromCaptureList(chosenUnit)
            end
          else
            if lastTile:getBuilding() ~= nil and lastTile:getBuilding():getOwnerObject() ~= currentPlayerTurn then
              captureBuilding:removeUnitFromCaptureList(chosenUnit)
            end
          end
        end
        return
      end
    end
  end   
  move:removeRange(chosenUnit:getMoveRange())
  rangeTurnedOn = false
  
  if attackHelper:attack(x,y,tile,tileProp, _clickedUnitProp, false) == false then
    self:removeAttackRanges()
  end
  
  if unitselectionProp ~= nil then
    MainLayer:removeProp(unitselectionProp)
    unitselectionProp = nil
  end
end

function ScreenActionHelper:removeAttackRanges()
  attackPossibilitiesOn = false
  attackHelper:removeAttackProps()
end

function ScreenActionHelper:showAttackRanges(range, x1, y1, x2, y2)
  attackPossibilitiesOn = true
  canUserClickAttack = true
  attackHelper:showAttackRange(range, x1, y1, x2, y2)
end

function ScreenActionHelper:showUnitSelection(unitObject)
    local selection = MOAIGfxQuad2D.new()
    selection:setRect(unitObject:getRectangleValues())
    
    if currentPlayerTurn == pl1 then
      selection:setTexture(textureSelectionRed)
    else
      selection:setTexture(textureSelectionBlue)
    end
    
    unitselectionProp = MOAIProp2D.new()
    unitselectionProp:setPriority(40)
    unitselectionProp:setDeck(selection)
    unitselectionProp:setBlendMode(MOAIProp.GL_SRC_ALPHA, MOAIProp.GL_ONE_MINUS_SRC_ALPHA)
    MainLayer:insertProp(unitselectionProp)
end

function ScreenActionHelper:notEnoughGold()
  if alreadyClicked == false then
    local notEnoughGold = MOAITextBox.new()
    notEnoughGold:setStyle(style)
    notEnoughGold:setRect(285, 0, -390, -390)
    notEnoughGold:setAlignment(MOAITextBox.LEFT_JUSTIFY, MOAITextBox.CENTER_JUSTIFY)
    notEnoughGold:setYFlip(true)
    notEnoughGold:setPriority(1000)
    notEnoughGold:setString("Not enough gold!")
    renderLayerTable[9] = notEnoughGold
    MainLayer:insertProp(notEnoughGold)
    alreadyClicked = true
    local timer = MOAITimer.new()
      timer:setMode(MOAITimer.NORMAL)
      timer:setSpan(1.5)
      timer:setListener(MOAITimer.EVENT_TIMER_END_SPAN, function() 
            renderLayerTable[9] = nil
            MainLayer:removeProp(notEnoughGold)
            alreadyClicked = false
      end)
      timer:start() 
    end
end

 return ScreenActionHelper